/*
  学习目标：TextArea自动获取光标在最后位置
 
*/

import classNames from "classnames";
import { useEffect, useRef } from "react";
import styles from "./index.module.scss";

interface ITextAreaProps
  extends React.DetailedHTMLProps<
    React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    HTMLTextAreaElement
  > {
  value?: string;
}

export default function Textarea({
  className,
  value,
  maxLength = 100,
  ...restProps
}: ITextAreaProps) {
  // 1. 创建ref, 绑定ref
  const txtRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    // 2. 挂载后, 自动激活
    txtRef.current?.focus();
    // 3. 挂载后设置选区范围
    txtRef.current?.setSelectionRange(-1, -1);
  }, []);

  return (
    <div className={styles.root}>
      <textarea
        ref={txtRef}
        className={classNames("textarea", className)}
        value={value}
        maxLength={maxLength}
        {...restProps}
      />
      <div className="count">
        {value?.length}/{maxLength}
      </div>
    </div>
  );
}
